<?php 
Import::appLibs("Configuration");
class AdvertController extends Controller {
	public function __construct(){
		$this->calledClass(get_class($this));
	}
	/* Mr. Chamroeun Oum
	 * Function to retrive all employers to build up employers table for ajax call
	*/
	public function adverts(){
		$advert = $this->loadModel("Advert");
		$page = $this->get("page")!=NULL?$this->get("page"):1;
		$perpage = $this->get("perpage")!=NULL?$this->get("perpage"):20;
		$search = $this->get("search")!=NULL?$this->get("search"):"";
		$position = $this->get("p");
		$this->set(array("position"=>$position));
		$this->set(array("positions"=>array(
				0=>"Select positions",
				1=>"Top Left",
				2=>"Top Center",
				3=>"Top Right",
				4=>"Middle Left",
				5=>"Middle Center",
				6=>"Middle Right",
				7=>"Bottom",
		)));
		$records = $advert->getList($page,$perpage,$search,array("name","url","owner","price"),array(),"",array("position="=>($position>0)?$position:NULL));
		$this->set(array("records"=>$records));
		$this->render("admin_display");
	}
	/*
	 * Author: Mr. Chamroeun OUM
	 * Function to retrie page change order of advertisement
	 * */
	public function adpageindexing(){
		$this->render("change-order");
	}
	/*
	 * Author: Mr. Chamroeun OUM
	* Function to retrieve page of group advertisements 
	* */
	public function groupads(){
		$position = $this->get("position");
		$advert = $this->loadModel("Advert");
		$records = $advert->getList(1,100,"",array("name","url","owner","price"),array("ad_index"),"ASC",array("position="=>$position));
		$this->set(array("position"=>$position,"records"=>$records));
		$this->render("ads_group");
	}
	
	public function pview(){
		if($this->get("id")!=NULL){
			$advert = $this->loadModel("Advert");
			$advertisement = $advert->findAsObject(array("id="=>$this->get("id")));
			$this->set(array("imgUrl"=>ROOT . $advertisement->images[0]->location));
			switch($advertisement->position){
				case 1:
				case 3:
				case 4:
				case 6:
					$this->render("adv200x200");
				break;
				case 2:
				case 5:
					$this->render("adv540x100");
				break;
				case 7:
					$this->render("adv700x120");
					break;
			}
		}
	}
	public function advertedit(){
		$advert = $this->loadModel("Advert");
		$advertisement = $advert->findAsObject(array("id="=>$this->get("id")));
		$this->set(array("advertisement"=>$advertisement));
		$this->set(array("allIndex"=>$advert->getIndexByPosition($advertisement->position)));
		$this->render("edit");
	}
	public function advertadd(){
		$this->render("add");
	}
	
	public function save(){
		Import::util("FileUpload");
		$user_id = 0; // Super admin
		$folder = "data/ads";
		if(!Basic::fileExist($folder))Basic::createFolder($folder);
		$gallery = $this->loadModel("Gallery");
		$infos=FileUpload::checkFileUpload($folder);
		$info = is_array($infos)&&!empty($infos)?$infos[0]:array();
		$helper = true;
		$record = NULL;
		$advert=$this->loadModel("Advert");
		$reCount = $advert->getMaxOrder($this->get("position"));
		print_r( $info );

		if($info["error"]["number"]==0){
			if(($record=$gallery->savephoto(array(
					"uid"=>$user_id,"gname"=>"admin","name"=>$info["name"],"type"=>$info["type"],"size"=>$info["size"],
					"d_w"=>$info["dimension"]["width"],"d_h"=>$info["dimension"]["height"],"location"=>"",
					"created"=>date("Y-m-d H:s:i"),"modified"=>date("Y-m-d H:s:i"))))!==false){
print_r( $record );
					$row_save = $advert->save(array(
							"url"=>$this->get("url"),
							"name"=>$this->get("name"),
							"owner"=>$this->get("owner"),
							"start"=>$this->get("start"),
							"stop" => date("Y-m-d",strtotime($this->get("start"))+($this->get("period")*86400)), // 86400 as second equal to 24 hours or 1 day
							"period"=>$this->get("period"),
							"position"=>$this->get("position"),
							"active"=>$this->get("active"),
							"price"=>$this->get("price"),
							"created"=>date("Y-m-d"),
							"ad_index"=>$reCount+1,
							"modified"=>date("Y-m-d"),
							"uid"=>$user_id,
							"img_id"=>$record->id));
print_r( $row_save );
					$gallery->update(array("location"=>$folder."/".$record->id.".".$info["ext"]),array("id="=>$record->id));
					FileUpload::uploadFile($info["control"],$record->id.".".$info["ext"],5,$folder);
			}
		}
//exit();
		$this->redirect(array("admin"=>"ads"));
	}

	public function update(){
		Import::util("FileUpload");
		$user_id = 7;
		$folder = "data/ads";
		$image = $this->get("gid");
		if(!Basic::fileExist($folder))Basic::createFolder($folder);
		$gallery = $this->loadModel("Gallery");
		$infos=FileUpload::checkFileUpload($folder);
		$info = is_array($infos)&&!empty($infos)?$infos[0]:array();
		$helper = true;

		if($info["error"]["number"]==0){
			$images = $gallery->findAsObject(array("id="=>$image));
			Basic::deleteFile($images->location);
			if(($record=$gallery->update(array(
					"name"=>$info["name"],
					"type"=>$info["type"],
					"size"=>$info["size"],
					"d_w"=>$info["dimension"]["width"],
					"d_h"=>$info["dimension"]["height"],
					"location"=>$folder."/".$image.".".$info["ext"],
					"modified"=>date("Y-m-d")),
					array("id="=>$image)))!==false){
				FileUpload::uploadFile($info["control"],$image.".".$info["ext"],5,$folder);
			}
		}
		//change index ordering of advertise
		$advert=$this->loadModel("Advert");
		$recordchanges = $advert->findAsObject(array("id="=>$this->get("gid")));
		$position = $this->get("position");
		if( $this->get("ordering") > $recordchanges->ad_index ){
			$recordUnderChagne = $advert->getAsObject(array("id","ad_index"),array("position="=>$position,"ad_index > "=>$recordchanges->ad_index,"ad_index<"=>$this->get("ordering")+1));
			foreach ($recordUnderChagne as $row){
				$advert->update(array("ad_index"=>$row->ad_index-1),array("id="=>$row->id,"position="=>$position));
			}
		}else{
			$recordUnderChagne = $advert->getAsObject(array("id","ad_index"),array("position="=>$position, "ad_index < "=>$recordchanges->ad_index,"ad_index>"=>($this->get("ordering") > 1)?$this->get("ordering")-1:"0"));
			foreach ($recordUnderChagne as $rowUnderChange){
				$advert->update(array("ad_index"=>$rowUnderChange->ad_index+1),array("id="=>$rowUnderChange->id,"position="=>$position));
			}
		}
		$advert->update(array("ad_index"=>$this->get("ordering"),"name"=>$this->get("name"),"owner"=>$this->get("owner"),"url"=>$this->get("url"),"start"=>$this->get("start"),"period"=>$this->get("period"),"active"=>$this->get("active"),"price"=>$this->get("price"),"modified"=>date("Y-m-d"),"uid"=>$user_id),array("id="=>$this->get("gid")));
		/* if($this->get("ordering")!=$advrecord){
			$advert->Indexing($advrecord,$this->get("ordering"),$this->get("position"),$this->get("gid"));
		} */
		if($helper){
		 $this->redirect(array("admin"=>"ads"));
		 echo "All file(s) are/is uploaded successfully.";
		}
	}
	public function remove(){
		$advert = $this->loadModel("Advert") ;
		$gallery = $this->loadModel("Gallery") ;
		$records = $advert->delete(array("id="=>$this->get("id")));
		foreach($records as $record ) $gallery->deletephoto(explode(",",$record->img_id),true) ;
	}
	/*
	 * Author: Mr. Pisey Phon
	* Function to switch index of group advertisements
	* */
	public function adSwitchIndex(){
		$position = $this->get("position");
		$from = $this->get("from_index");
		$to = $this->get("to_index");
		if($position){
			$advert = $this->loadModel("Advert");
			$recordchanges = $advert->findObject(array("ad_index = "=>$from,"position="=>$position));
			if($recordchanges){
				$version = ($recordchanges)?$recordchanges->version:0 + 1;
				if( $to > $recordchanges->ad_index ){
					$recordUnderChagne = $advert->getAsObject(array("id","ad_index"),array("position="=>$position,"ad_index > "=>$recordchanges->ad_index,"ad_index<"=>$to+1));
					foreach ($recordUnderChagne as $row){
						$advert->update(array("ad_index"=>$row->ad_index-1),array("id="=>$row->id,"position="=>$position));
					}
				}else{
					$recordUnderChagne = $advert->getAsObject(array("id","ad_index"),array("position="=>$position, "ad_index < "=>$recordchanges->ad_index,"ad_index>"=>($to > 1)?$to-1:"0"));
					foreach ($recordUnderChagne as $rowUnderChange){
						$advert->update(array("ad_index"=>$rowUnderChange->ad_index+1),array("id="=>$rowUnderChange->id,"position="=>$position));
					}
				}
				//Edit field when user input
				$row = $advert->update(array(
						"ad_index"=>trim($to),
						"version"=>$version,
						"modified"=>date("Y-m-d H:i:s")),array("id = "=>$recordchanges->id,"position="=>$position));
			}
			$records = $advert->getList(1,100,"",array("name","url","owner","price"),array("ad_index"),"ASC",array("position="=>$position));
			$this->set(array("position"=>$position,"records"=>$records));
			$this->render("ads_group");
		}
	}
}
